// findDoctor/pages/doctorDetail/doctorDetail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoList: [],
    articleList:[],
    doctor:{},
    isLoading: false,
    pageSize: 20, // 每页条数
    pageNo: 1, // 当前页码，从1开始
    total: 0, // 总记录数（可选）
    pageCount: 0, // 总页数（从后端返回，判断是否还有下一页）
    isFollowed: false, // 新增：关注状态
    doctorFollowId: null, // 新增，用于保存关注关系的ID
    userId: null
  },

  toMoreArticle() {
    wx.navigateTo({
      url: '/findDoctor/pages/moreArticle/moreArticle',
    })
  },

  toMessage(e){
    const { id } = e.currentTarget.dataset;
    console.log('点击的医生id是:',id);
    wx.navigateTo({
      url: `/findDoctor/pages/message/message?id=${id}`,
    })
  },
  // toVideoDetail(){
  //   wx.navigateTo({
  //     url: '/findDoctor/pages/videoDetail/videoDetail',
  //   })
  // },

  toMoreAppraise() {
    wx.navigateTo({
      url: '/findDoctor/pages/doctorAppraise/doctorAppraise',
    })
  },
  toInfo(e) {
    const { id } = e.currentTarget.dataset;
    console.log('点击的医生id是:',id);
    wx.navigateTo({
      url: `/findDoctor/pages/doctorInfo/doctorInfo?id=${id}`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id } = options;
    const app = getApp();
    let userId = app.globalData.userId;
    this.setData({ userId });

    this.getDoctorData(id)
  },

  getDoctorData(id) {
    const app = getApp();
    const token = app.globalData.token;
    const userId = app.globalData.userId;
    
    wx.showLoading({
      title: '数据正在加载...',
    })
    wx.request({
      url: `http://localhost:8080/doctor/doctor/${id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}` // 添加Bearer前缀
      },
      success: (resp) => {
        console.log('医生详情数据:', resp);
        const doctor = resp.data.data;
      // 顺便请求该用户是否已关注
      this.checkFollowFromServer(doctor.id, userId);

        this.setData({
          doctor,
          articleList:resp.data.data.articleList,
          videoList:resp.data.data.videoList
        })
      },
      complete: () => {
        wx.hideLoading(),
        wx.stopPullDownRefresh()
      }
    })
  },

 // 从后端获取是否关注
  checkFollowFromServer(doctorId, userId) {
    const app = getApp();
    const token = app.globalData.token;

    wx.request({
      url: `http://localhost:8080/doctor/follow/status?doctorId=${doctorId}&patientId=${userId}`,
      method: 'GET',
      header: { 'Authorization': `Bearer ${token}` },
      success: (resp) => {
        console.log('关注信息',resp)
        if (resp.statusCode === 200 && resp.data.code === 200) {
          this.setData({
            isFollowed: resp.data.data.isFollowed,
            doctorFollowId: resp.data.data.followId || null
          });
        }
      }
    });
  },
  /**
   * 关注按钮函数
   */
  // 点击关注/取消关注
  toggleFollow() {
    const doctorId = this.data.doctor.id;
    const userId = this.data.userId;
    const isFollowed = !this.data.isFollowed;

    if (isFollowed) {
      this.followDoctor(doctorId, userId);
    } else {
      this.unfollowDoctor();
    }
  },

  // 关注医生
  followDoctor(doctorId, userId) {
    const app = getApp();
    const token = app.globalData.token;

    wx.request({
      url: `http://localhost:8080/doctor/follow`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: { doctorId, patientId: userId },
      success: (resp) => {
        console.log('关注结果:', resp);
        if (resp.statusCode === 200 && resp.data.code === 200) {
          wx.showToast({ title: '关注成功', icon: 'success' });
          this.setData({
            isFollowed: true,
            doctorFollowId: resp.data.data.followId
          });
        } else {
          wx.showToast({ title: resp.data.message || '关注失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误，关注失败', icon: 'none' });
      }
    });
  },

  // 取消关注医生
  unfollowDoctor() {
    const app = getApp();
    const token = app.globalData.token;
    const followId = this.data.doctorFollowId;

    if (!followId) {
      wx.showToast({ title: '未找到关注记录', icon: 'none' });
      return;
    }

    wx.request({
      url: `http://localhost:8080/doctor/follow/${followId}`,
      method: 'DELETE',
      header: { 'Authorization': `Bearer ${token}` },
      success: (resp) => {
        console.log('取消关注结果:', resp);
        if (resp.statusCode === 200 && resp.data.code === 200) {
          wx.showToast({ title: '已取消关注', icon: 'success' });
          this.setData({
            isFollowed: false,
            doctorFollowId: null
          });
        } else {
          wx.showToast({ title: resp.data.message || '取消失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误，取消失败', icon: 'none' });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    
  },
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})